package com.example.channel

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.channels.Channel
import org.junit.Test


/**
 * 广播通道测试
 *
 * @author zhouronghua
 * @time 2022/1/8 8:41 下午
 */
class BroadcastChannelTest {

    /**
     * 测试广播通道发送消息
     * 说明：广播通道发送消息，三个协程进行接收
     * 说明：发送的广播不是粘滞的，发送时没有接收者则消息丢失
     *
     * @author zhouronghua
     * @time 2022/1/8 8:41 下午
     */
    @Test
    fun test_broadcast_channel_send() = runBlocking {
        println("测试通道广播功能")
        val broadcastChannel = BroadcastChannel<Int>(Channel.BUFFERED)
        // 生产者通过广播通道发送三个元素
        val producer = GlobalScope.launch {
            for (i in 1..3) {
                println("BroadcastChannel send $i")
                delay(100)
                broadcastChannel.send(i)
            }
            broadcastChannel.close()
        }
        // 开启三个订阅协程
        List(3) { index ->
            GlobalScope.launch {
                // 协程接收元素
                // 开启广播通道订阅者
                val receiveChannel = broadcastChannel.openSubscription()
                for (element in receiveChannel) {
                    println("[#$index] receive $element")
                }

            }
        }.joinAll()
        producer.join()
    }


}